import http.client
import hashlib
import urllib
import random
import json
import tkinter as tk


def getString(word) :

    try:
        appid = '百度密钥的id'  # 冯id
        secretKey = '百度密钥'  # 冯:密钥

        httpClient = None
        url = '/api/trans/vip/translate'

        fromLang = 'auto'  # 原文语种
        toLang = 'auto'  # 译文语种
        salt = random.randint(32768, 65536)
        q = str(word)
        sign = appid + q + str(salt) + secretKey
        sign = hashlib.md5(sign.encode()).hexdigest()
        myurl = url + '?appid=' + appid + '&q=' + urllib.parse.quote(
            q) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(
            salt) + '&sign=' + sign
        values = ""
        httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
        httpClient.request('GET', myurl)

        # response是HTTPResponse对象
        response = httpClient.getresponse()
        result_all = response.read().decode("utf-8")
        result = json.loads(result_all)

        print(result)
        print(myurl)
        return result['trans_result'][0]['dst']

    except Exception as e:
        print(e)
    finally:
        if httpClient:
            httpClient.close()


print(getString("请输入你要翻译的东西"))

window = tk.Tk()
window.title("万能翻译")
window.geometry('700x700')
canvas = tk.Canvas(window, height=1920, width=1080)
canvas.pack()
text=tk.StringVar();

l1 = tk.Label(window,textvariable=text,font=('宋体','20'))
l1.place(x=100,y=260)
l2 = tk.Label(window,text="请输入需要翻译的中文",font=('宋体','20'))
l2.place(x=100,y=90)
tbox = tk.Entry(window,show=None,font=('宋体','20'),text='请输入你要翻译的东西(汉译英)')
tbox.place(x=100,y=130)
l3 = tk.Label(window,text="结果:",font=('宋体','20'))
l3.place(x=100,y=220)



flag = True
index = '1'
def isFlag():
    global flag
    global index
    if tbox.get()=='':
        text.set("不能为空")
    else :
        text.set(getString(tbox.get()))

btn = tk.Button(window,text="点我切换",font=('宋体',20),command = isFlag)
btn.place(x=500,y=100)



window.mainloop()